import grails.test.*

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.Method.POST
import static groovyx.net.http.ContentType.TEXT
import static groovyx.net.http.ContentType.HTML

class RankInfoTests extends GrailsUnitTestCase {
    protected void setUp() {
        super.setUp()
    }

    protected void tearDown() {
        super.tearDown()
    }
    
    // 네이트 뉴스 1~5위  
    void testParsingNateTopNews() {
    	def htmlNewsMain = new HTTPBuilder('http://news.nate.com').request(GET,TEXT) { uri.path = '/rank/interest' }
        assert htmlNewsMain instanceof Reader // response data is buffered in-memory
        def slurper = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser())
		
    	def html = slurper.parse(htmlNewsMain)
		def articles = html.body.div.div.div.div.div.div.findAll{ it.@class == 'mduSubjectList f_clear' }	
		
		assert articles.list().size() == 5
		
		articles.list().each { article ->
			String rank = article.dl.dt.em
			String thumbnailLink = article.div.a.img.@src
			String link = article.dl.dt.a.@href
			String title = article.dl.dt.a.strong
			
			assert rank
			assert link
			assert title
			
			println "$rank $title - $link"
		}
    }
	
    // 네이트 뉴스 6~30위 
    void testParsingNateNews() {
    	def htmlNewsMain = new HTTPBuilder('http://news.nate.com').request(GET,TEXT) { uri.path = '/rank/interest' }
        assert htmlNewsMain instanceof Reader // response data is buffered in-memory
        def slurper = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser())
		
    	def html = slurper.parse(htmlNewsMain)
		def sessions = html.body.div.div.div.div.div.ul.findAll{ it.@class == 'mduSubject mduRankSubject' }
		
    	sessions.list().each { articles ->
    		articles.li.list().each { article ->
				String rank = article.dl.dt.em
				String thumbnailLink = article.div.a.img.@src
				String link = article.a.@href
				String title = article.a.text()
				
				assert rank
				assert link
				assert title
				
				println "$rank $title - $link"
			}
		}
    }
    
    // 랭킹뉴스 순위, 제목, 기사ID 파싱 테스트 
    void testParsingRankInfo() {
    	['all', 'sisa', 'ent', 'spo', 'its'].each { section ->
			def rankInfo = RankInfo.parseRankInfo(section, new Date().format('yyyyMMdd').toString())
			println "section:$rankInfo.section, dateCreated:$rankInfo.dateCreated"
	    	
			for(articleRank in rankInfo.listOfArticleRank.sort { it.rank }) {
				println "$articleRank.rank 위, $articleRank.articleTitle ($articleRank.articleId)"
			}
    	}
    }
}
